﻿using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Core.BOL;
using Core.Extentions;
using Core.ScheduleTask;
using Core.Utils;
using ScoutNET.Attributes;
using Core.DAL;
using System.Net;

namespace ScoutNET.Controllers
{
    [HandleErrorWithELMAHAttribute]
    public class GlobalController : Controller
    {
        #region Views
        public ActionResult CSSwitcher()
        {
            int currentMonth = DateTime.Now.GetNowTimeByTimeZone().Month;
            int currentDay = DateTime.Now.GetNowTimeByTimeZone().Day;
            int currentTimeID = GetTimeID();
            string holidayCss = string.Empty;
            string color = string.Empty;

            // Change bg color and footer
            if ((currentMonth == 12 && currentDay >= 5) || (currentMonth == 1 && currentDay <= 10))
            {
                holidayCss = @"
		        body{{ background:url(/Design/Images/TemplateSwitcher/landscape1_pattern.png) bottom fixed repeat-x #CBE7F5;}}
		        #footer{{ text-align:center; color:#000; font-size:11px; padding:0 0 20px 220px; margin-top:10px;}}
		        #footer a,
		        #footer a:link,
		        #footer a:active,
		        #footer a:visited{{ text-decoration:underline; color:#000}}
		        #footer a:hover{{ text-decoration:none;}}";
                holidayCss += string.Format(@"#bgContent{{background:url('/Design/Images/TemplateSwitcher/bgBody{0}.jpg') fixed repeat-x;}}", "5");
            }
            else
            {
                switch (GetTimeID())
                {
                    case 1:
                        color = "#D0DEE7";
                        break;
                    case 2:
                        color = "#2ea6d9";
                        break;
                    case 3:
                        color = "#C7DFFB";
                        break;
                    case 4:
                        color = "#FFE574";
                        break;
                }

                holidayCss = string.Format(@"
		        body{{ background:url(/Design/Images/TemplateSwitcher/landscape1_pattern.png) bottom fixed repeat-x {0}; }}
		        #footer{{ text-align:center; color:#fff; font-size:11px; padding:0 0 20px 220px; margin-top:10px;}}
		        #footer a,
		        #footer a:link,
		        #footer a:active,
		        #footer a:visited{{ text-decoration:underline; color:#fff}}
		        #footer a:hover{{ text-decoration:none;}}", color);
                holidayCss += string.Format(@"#bgContent{{background:url('/Design/Images/TemplateSwitcher/bgBody{0}.jpg') fixed repeat-x;}}", currentTimeID.ToString());
            }

            // Change logo
            if (currentMonth == 10 && (currentDay >= 10 && currentDay <= 31))
            {
                holidayCss += "div#logo{ background:url(/Design/Images/TemplateSwitcher/halloweenLogo.png) no-repeat;}";
            }
            else if ((currentMonth == 12 && currentDay >= 5) || (currentMonth == 1 && currentDay <= 10))
            {
                holidayCss += "div#logo{ background:url(/Design/Images/TemplateSwitcher/xmasLogo.png) no-repeat;}";
            }
            else
            {
                holidayCss += "div#logo{ background:url(/Design/Images/TemplateSwitcher/logo.png) no-repeat;}";
            }

            return this.Content(holidayCss.Trim(), "text/css", Encoding.UTF8);
        }

        public FileResult MailsStats(Guid MailID, Guid UserID)
        {
            StatViewsRepository svr = new StatViewsRepository();

            svr.AddView(MailID, UserID);
            svr.Save();

            byte[] baImage = Files.FileToArray(HttpContext.Server.MapPath("/Design/Images/SiteImages/spacer.gif"));
            return new FileContentResult(baImage, "image/jpeg");
        }

        public ActionResult Error404()
        {
            Response.TrySkipIisCustomErrors = true;
            Response.StatusDescription = HttpStatusCode.NotFound.ToString();
            Response.StatusCode = 404;  

            string[] saBreadcrumb = new String[2];

            if(ControllerContext.HttpContext.Request.Url.ToString().EndsWith(".zip"))
            {
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = Resources.Error_ErrorFileZIP_Breadcrumb;
                ViewData["Breadcrumb"] = saBreadcrumb;
                
                ViewData["PageTitle"] = Resources.Error_ErrorFileZIP_Title;
                ViewData["PageDescription"] = Resources.Error_ErrorFileZIP_Description;

                return View("ErrorFileZIP");
            }

            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Error_Error404_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            ViewData["PageTitle"] = Resources.Error_Error404_Title;
            ViewData["PageDescription"] = Resources.Error_Error404_Description;

            return View();
        }

        public ActionResult Error500()
        {
            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Error_Error500_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            ViewData["PageTitle"] = Resources.Error_Error500_Title;
            ViewData["PageDescription"] = Resources.Error_Error500_Description;

            Response.TrySkipIisCustomErrors = true;
            Response.StatusDescription = HttpStatusCode.InternalServerError.ToString();
            Response.StatusCode = 500;

            return View();
        }

        public EmptyResult ScheduledTask(string param)
        {
            if (!string.IsNullOrEmpty(param))
            {
                // Add events mail to the mail queue
                if (param.ToLower().Contains("AgendaMail".ToLower()))
                {
                    AgendaMail.Proceed();
                }

                //Create Mail HTML
                if (param.ToLower().Contains("GenerateMail".ToLower()))
                {
                    GenerateMail.Proceed();
                }

                // Batch to send de mail in the queue
                if (param.ToLower().Contains("SendMailQueue".ToLower()))
                {
                    SendMailQueue.Proceed();
                }
            }

            return new EmptyResult();
        }

        [HttpPost]
        [Authorize(Roles = "Animateur,C.U")]
        public int UnreadMailCount()
        {
            SectionRepository sr = new SectionRepository();

            tSite_Section s = sr.GetUserSectionByUserAndRole();
            if (s != null)
            {
                Core.Utils.GmailClient client = new Core.Utils.GmailClient(s.EmailLogin, s.EmailPassword);
                client.GetUnreadMail();
                Session["UnreadMailCount"] = client.UnreadMailCount;
                return (int)Session["UnreadMailCount"];
            }

            return 0;
        }
        #endregion

        #region Private methodes
        private static int GetTimeID()
        {
            bool isDaylightSavingTime = DateTime.Now.GetNowTimeByTimeZone().IsDaylightSavingTime();
            int currentTime = DateTime.Now.GetNowTimeByTimeZone().Hour;

            if (isDaylightSavingTime)
            {
                if (currentTime >= 6 && currentTime <= 9)          //	6  -> 9
                {
                    return 3;
                }
                else if (currentTime >= 10 && currentTime <= 18)    //  10 -> 19
                {
                    return 1;
                }
                else if (currentTime >= 19 && currentTime <= 21)    //	19 -> 22
                {
                    return 4;
                }
                else                                                //  22 -> 6
                {
                    return 2;
                }
            }
            else
            {
                if (currentTime >= 6 && currentTime <= 10)          //	6  -> 10
                {
                    return 3;
                }
                else if (currentTime >= 11 && currentTime <= 16)    //  11 -> 16
                {
                    return 1;
                }
                else if (currentTime >= 17 && currentTime <= 19)    //	17 -> 19
                {
                    return 4;
                }
                else                                                //  20 -> 6
                {
                    return 2;
                }
            }
        }
        #endregion
    }
}
